package com.zhoutian.service.Impl;

import com.zhoutian.service.EmailSendService;
import com.zhoutian.utils.Transit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Slf4j
@Service
public class EmailSendServiceImpl implements EmailSendService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendEmail(String to, Transit transit) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(to);
            helper.setFrom(from);
            helper.setSubject("注册验证码");
            String text = "验证码为: " + transit.getCheckCode();
            helper.setText(text);
            mailSender.send(mimeMessage);
            log.info("已发送邮件");
        } catch (MessagingException e) {
            e.printStackTrace();
            log.error("邮件发送错误");
        }
    }
}
